package com.campus.help.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campus.help.entity.Labor;
import com.campus.help.entity.LaborApplication;
import com.campus.help.entity.Student;
import com.campus.help.entity.LaborType;
import com.campus.help.mapper.LaborApplicationMapper;
import com.campus.help.mapper.LaborMapper;
import com.campus.help.mapper.LaborTypeMapper;
import com.campus.help.mapper.StudentMapper;
import com.campus.help.vo.LaborVO;
import org.springframework.beans.BeanUtils;
import com.campus.help.service.LaborService;
import com.campus.help.service.MessageService;
import com.campus.help.vo.LaborApplicationVO;
import com.campus.help.common.LaborApplicationStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 劳务服务实现类
 *
 * @author campus-help
 * @since 2025-09-18
 */
@Slf4j
@Service
public class LaborServiceImpl implements LaborService {

    @Autowired
    private LaborMapper laborMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private LaborApplicationMapper laborApplicationMapper;
    @Autowired
    private LaborTypeMapper laborTypeMapper;
    @Autowired
    private MessageService messageService;

    @Override
    public Page<Labor> getLaborList(int page, int size, String keyword, String location, String workType, Boolean urgent, String date) {
        Page<Labor> pageParam = new Page<>(page, size);

        QueryWrapper<Labor> queryWrapper = new QueryWrapper<>();

        // 只显示招聘中的劳务
        queryWrapper.eq("deleted", 0);

        // 搜索关键词
        if (keyword != null && !keyword.trim().isEmpty()) {
            queryWrapper.and(wrapper -> wrapper
                    .like("job_title", keyword)
                    .or()
                    .like("description", keyword)
                    .or()
                    .like("requirements", keyword)
            );
        }
        // 地点筛选
        if (location != null && !location.trim().isEmpty()) {
            queryWrapper.eq("location", location);
        }

        // 工作类型筛选
        if (workType != null && !workType.trim().isEmpty()) {
            queryWrapper.eq("work_type", workType);
        }

        // 紧急筛选
        if (urgent != null) {
            queryWrapper.eq("urgent", urgent ? 1 : 0);
        }

        // 日期筛选
        if (date != null && !date.trim().isEmpty()) {
            try {
                // 将日期字符串转换为LocalDate
                java.time.LocalDate targetDate = java.time.LocalDate.parse(date);
                // 设置查询条件的开始时间（当天00:00:00）
                java.time.LocalDateTime startTime = targetDate.atStartOfDay();
                // 设置查询条件的结束时间（当天23:59:59）
                java.time.LocalDateTime endTime = targetDate.atTime(23, 59, 59);

                queryWrapper.between("create_time", startTime, endTime);
            } catch (Exception e) {
                log.warn("日期格式错误，忽略日期筛选: {}", date);
            }
        }

        // 按创建时间倒序
        queryWrapper.orderByDesc("create_time");

        Page<Labor> laborPage = laborMapper.selectPage(pageParam, queryWrapper);

        if (!CollectionUtils.isEmpty(laborPage.getRecords())) {
            laborPage.getRecords().forEach(labor -> {
                Student student = studentMapper.selectById(labor.getPublisherId());
                if (student != null) {
                    labor.setPublisher(student.getNickname());
                }

                Long count = laborApplicationMapper.selectCount(new LambdaQueryWrapper<LaborApplication>().eq(LaborApplication::getLaborId, labor.getId()));
                labor.setApplicationCount(count);

            });
        }

        return laborPage;
    }

    @Override
    public Page<LaborVO> getLaborListWithType(int page, int size, String keyword, Long typeId, String location, String workType, Boolean urgent, String date, Long schoolId) {
        // 先获取Labor分页数据，并添加typeId筛选
        Page<Labor> laborPage = getLaborListWithTypeFilter(page, size, keyword, typeId, location, workType, urgent, date, schoolId);

        // 创建LaborVO分页对象
        Page<LaborVO> laborVOPage = new Page<>(laborPage.getCurrent(), laborPage.getSize(), laborPage.getTotal());

        // 转换Labor为LaborVO，并添加类型信息
        List<LaborVO> laborVOList = laborPage.getRecords().stream()
                .map(this::convertToLaborVO)
                .collect(java.util.stream.Collectors.toList());

        laborVOPage.setRecords(laborVOList);
        return laborVOPage;
    }

    /**
     * 获取劳务列表（支持typeId筛选）
     */
    private Page<Labor> getLaborListWithTypeFilter(int page, int size, String keyword, Long typeId, String location, String workType, Boolean urgent, String date, Long schoolId) {
        Page<Labor> pageParam = new Page<>(page, size);

        QueryWrapper<Labor> queryWrapper = new QueryWrapper<>();

        // 只显示招聘中的劳务
        queryWrapper.eq("deleted", 0);

        // 学校ID过滤（数据隔离）
        if (schoolId != null) {
            queryWrapper.eq("school_id", schoolId);
            log.info("添加学校ID过滤: schoolId={}", schoolId);
        } else {
            log.info("未提供学校ID，返回所有学校的劳务（未登录用户访问）");
        }

        // 搜索关键词
        if (keyword != null && !keyword.trim().isEmpty()) {
            queryWrapper.and(wrapper -> wrapper
                    .like("job_title", keyword)
                    .or()
                    .like("description", keyword)
                    .or()
                    .like("requirements", keyword)
            );
        }

        // 劳务类型筛选
        if (typeId != null) {
            queryWrapper.eq("type_id", typeId);
        }

        // 地点筛选
        if (location != null && !location.trim().isEmpty()) {
            queryWrapper.eq("location", location);
        }

        // 工作类型筛选
        if (workType != null && !workType.trim().isEmpty()) {
            queryWrapper.eq("work_type", workType);
        }

        // 紧急筛选
        if (urgent != null) {
            queryWrapper.eq("urgent", urgent ? 1 : 0);
        }

        // 日期筛选
        if (date != null && !date.trim().isEmpty()) {
            try {
                // 将日期字符串转换为LocalDate
                java.time.LocalDate targetDate = java.time.LocalDate.parse(date);
                // 设置查询条件的开始时间（当天00:00:00）
                java.time.LocalDateTime startTime = targetDate.atStartOfDay();
                // 设置查询条件的结束时间（当天23:59:59）
                java.time.LocalDateTime endTime = targetDate.atTime(23, 59, 59);

                queryWrapper.between("create_time", startTime, endTime);
            } catch (Exception e) {
                log.warn("日期格式错误，忽略日期筛选: {}", date);
            }
        }

        // 按创建时间倒序
        queryWrapper.orderByDesc("create_time");

        Page<Labor> laborPage = laborMapper.selectPage(pageParam, queryWrapper);

        if (!CollectionUtils.isEmpty(laborPage.getRecords())) {
            laborPage.getRecords().forEach(labor -> {
                Student student = studentMapper.selectById(labor.getPublisherId());
                if (student != null) {
                    labor.setPublisher(student.getNickname());
                }

                Long count = laborApplicationMapper.selectCount(new LambdaQueryWrapper<LaborApplication>().eq(LaborApplication::getLaborId, labor.getId()));
                labor.setApplicationCount(count);

            });
        }

        return laborPage;
    }

    /**
     * 将Labor转换为LaborVO，包含类型信息
     */
    private LaborVO convertToLaborVO(Labor labor) {
        LaborVO laborVO = new LaborVO();
        BeanUtils.copyProperties(labor, laborVO);

        // 设置基本属性
        laborVO.setPublisherName(labor.getPublisher());
        laborVO.setApplicationCount(labor.getApplicationCount() != null ? labor.getApplicationCount().intValue() : 0);
        laborVO.setIsUrgent(labor.getUrgent() == 1);

        // 确保publisherType不为null
        // 如果publisherType为空，根据merchantId是否存在来判断
        if (labor.getPublisherType() == null || labor.getPublisherType().isEmpty()) {
            if (labor.getMerchantId() != null && labor.getMerchantId() > 0) {
                labor.setPublisherType("merchant");
            } else {
                labor.setPublisherType("student");
            }
        }
        laborVO.setPublisherType(labor.getPublisherType());

        // 获取并设置类型信息
        if (labor.getTypeId() != null) {
            LaborType laborType = laborTypeMapper.selectById(labor.getTypeId());
            if (laborType != null) {
                laborVO.setTypeName(laborType.getTypeName());
                laborVO.setTypeIcon(laborType.getIcon());
                laborVO.setTypeColor(laborType.getColor());
            }
        }

        return laborVO;
    }

    @Override
    public Labor getLaborDetail(Long id) {
        Labor labor = laborMapper.selectById(id);
        if (labor != null && labor.getDeleted() == 0) {
            // 设置申请人数
            Long count = laborApplicationMapper.selectCount(new LambdaQueryWrapper<LaborApplication>().eq(LaborApplication::getLaborId, labor.getId()));
            labor.setApplicationCount(count);

            // 获取发布者详细信息
            if (labor.getPublisherId() != null) {
                Student publisher = studentMapper.selectById(labor.getPublisherId());
                if (publisher != null) {
                    labor.setPublisher(publisher.getNickname() != null ? publisher.getNickname() : "匿名用户");
                    // 注意：这里添加发布者信用分等信息到Labor对象的扩展字段中
                    // 由于Labor实体没有这些字段，我们需要用其他方式传递
                }
            }

            return labor;
        }
        return null;
    }

    @Override
    public com.campus.help.vo.LaborDetailVO getLaborDetailWithPublisher(Long id) {
        Labor labor = laborMapper.selectById(id);
        if (labor == null || labor.getDeleted() == 1) {
            return null;
        }

        com.campus.help.vo.LaborDetailVO detailVO = new com.campus.help.vo.LaborDetailVO();

        // 复制劳务基本信息
        detailVO.setId(labor.getId());
        detailVO.setJobTitle(labor.getJobTitle());
        detailVO.setTypeId(labor.getTypeId());
        detailVO.setLocation(labor.getLocation());
        detailVO.setWorkType(labor.getWorkType());
        detailVO.setSalary(labor.getSalary());
        detailVO.setDescription(labor.getDescription());
        detailVO.setRequirements(labor.getRequirements());
        detailVO.setStatus(labor.getStatus());
        detailVO.setUrgent(labor.getUrgent());
        detailVO.setViewCount(labor.getViewCount());
        detailVO.setRequiredCount(labor.getRequiredCount());
        detailVO.setQq(labor.getQq());
        detailVO.setPhone(labor.getPhone());
        detailVO.setWechat(labor.getWechat());
        detailVO.setCreateTime(labor.getCreateTime());
        detailVO.setPublisherId(labor.getPublisherId());

        // 处理图片数据
        if (labor.getImages() != null && !labor.getImages().trim().isEmpty()) {
            try {
                // 将JSON字符串转换为字符串数组
                String[] imageArray = labor.getImages().split(",");
                detailVO.setImages(imageArray);
            } catch (Exception e) {
                log.warn("解析图片数据失败: {}", labor.getImages(), e);
            }
        }

        // 设置申请人数
        Long count = laborApplicationMapper.selectCount(new LambdaQueryWrapper<LaborApplication>().eq(LaborApplication::getLaborId, labor.getId()));
        detailVO.setApplicationCount(count);

        // 获取劳务类型信息
        if (labor.getTypeId() != null) {
            com.campus.help.entity.LaborType laborType = laborTypeMapper.selectById(labor.getTypeId());
            if (laborType != null) {
                detailVO.setTypeName(laborType.getTypeName());
                detailVO.setTypeIcon(laborType.getIcon());
                detailVO.setTypeColor(laborType.getColor());
            }
        }

        // 获取发布者详细信息
        if (labor.getPublisherId() != null) {
            Student publisher = studentMapper.selectById(labor.getPublisherId());
            if (publisher != null) {
                detailVO.setPublisherName(publisher.getNickname() != null ? publisher.getNickname() : "匿名用户");
                detailVO.setPublisherAvatar(publisher.getAvatarUrl());
                detailVO.setPublisherCredit(publisher.getCreditScore() != null ? publisher.getCreditScore() : 100);
                // 如果有学校信息，可以设置学校名称
                detailVO.setPublisherCollege("未设置学校"); // 暂时设置默认值
                detailVO.setPublisherPhone(publisher.getPhone());
                detailVO.setPublisherQq(publisher.getQq());
                detailVO.setPublisherWechat(publisher.getWechat());
            }
        }

        log.info("获取劳务详情成功: laborId={}, publisherCredit={}", id, detailVO.getPublisherCredit());
        return detailVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Labor publishLabor(Labor labor, Long publisherId, Long schoolId) {
        // 设置发布者ID
        labor.setPublisherId(publisherId);
        labor.setPublisherType("student");
        labor.setStatus("recruiting");
        labor.setViewCount(0);
        labor.setApplyCount(0);
        labor.setAcceptedCount(0);

        // 设置学校ID（数据隔离）
        labor.setSchoolId(schoolId);
        log.info("设置劳务学校ID: schoolId={}", schoolId);

        // 设置默认值
        if (labor.getRequiredCount() == null) {
            labor.setRequiredCount(1);
        }

        laborMapper.insert(labor);

        log.info("发布劳务成功: laborId={}, publisherId={}, schoolId={}, jobTitle={}, typeId={}",
                labor.getId(), publisherId, schoolId, labor.getJobTitle(), labor.getTypeId());

        return labor;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Labor updateLabor(Labor labor, Long publisherId) {
        // 验证发布者权限
        Labor existingLabor = laborMapper.selectById(labor.getId());
        if (existingLabor == null || !existingLabor.getPublisherId().equals(publisherId)) {
            throw new RuntimeException("无权限修改此劳务");
        }

        if (existingLabor.getDeleted() == 1) {
            throw new RuntimeException("劳务不存在");
        }

        // 更新劳务信息
        laborMapper.updateById(labor);

        log.info("更新劳务成功: laborId={}, publisherId={}", labor.getId(), publisherId);

        return labor;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean closeLabor(Long id, Long publisherId) {
        Labor labor = laborMapper.selectById(id);
        if (labor == null || !labor.getPublisherId().equals(publisherId)) {
            throw new RuntimeException("无权限关闭此劳务");
        }

        if (labor.getDeleted() == 1) {
            throw new RuntimeException("劳务不存在");
        }

        labor.setStatus("closed");
        laborMapper.updateById(labor);

        log.info("关闭劳务成功: laborId={}, publisherId={}", id, publisherId);

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public LaborApplication applyLabor(Long laborId, Long applicantId, String applicationNote) {
        // 检查劳务是否存在且可申请
        Labor labor = laborMapper.selectById(laborId);
        if (labor == null || labor.getDeleted() == 1) {
            throw new RuntimeException("劳务不存在");
        }

        if (!"recruiting".equals(labor.getStatus())) {
            throw new RuntimeException("劳务已关闭，无法申请");
        }

        // 检查是否已经申请过
        QueryWrapper<LaborApplication> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("labor_id", laborId);
        queryWrapper.eq("applicant_id", applicantId);
        queryWrapper.eq("deleted", 0);

        LaborApplication existingApplication = laborApplicationMapper.selectOne(queryWrapper);
        if (existingApplication != null) {
            throw new RuntimeException("您已经申请过此劳务");
        }

        // 创建申请记录
        LaborApplication application = new LaborApplication();
        application.setLaborId(laborId);
        application.setApplicantId(applicantId);
        application.setApplicationTime(LocalDateTime.now());
        application.setStatus("pending");
        application.setApplicationNote(applicationNote);

        laborApplicationMapper.insert(application);

        // 更新申请次数
        labor.setApplyCount(labor.getApplyCount() + 1);
        laborMapper.updateById(labor);

        // 发送申请通知消息给发布者
        try {
            Student applicant = studentMapper.selectById(applicantId);
            String applicantName = applicant != null ? applicant.getNickname() : "未知用户";

            messageService.sendLaborApplicationMessage(
                    labor.getPublisherId(),
                    laborId,
                    labor.getJobTitle(),
                    applicantName,
                    applicantId
            );
        } catch (Exception e) {
            log.warn("发送申请通知消息失败: {}", e.getMessage());
        }

        log.info("申请劳务成功: laborId={}, applicantId={}, applicationId={}",
                laborId, applicantId, application.getId());

        return application;
    }

    @Override
    public List<LaborApplicationVO> getLaborApplications(Long laborId, Long publisherId) {
        // 验证发布者权限
        Labor labor = laborMapper.selectById(laborId);


        QueryWrapper<LaborApplication> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("labor_id", laborId);
        queryWrapper.eq("deleted", 0);
        queryWrapper.orderByDesc("application_time");

        List<LaborApplication> applications = laborApplicationMapper.selectList(queryWrapper);

        // 转换为VO对象，包含申请者联系方式
        return applications.stream().map(application -> {
            LaborApplicationVO vo = new LaborApplicationVO();
            vo.setId(application.getId());
            vo.setLaborId(application.getLaborId());
            vo.setJobTitle(labor.getJobTitle());
            vo.setApplicantId(application.getApplicantId());
            vo.setApplicationTime(application.getApplicationTime());
            vo.setStatus(application.getStatus());
            vo.setStatusDescription(LaborApplicationStatus.fromCode(application.getStatus()).getDescription());
            vo.setApplicationNote(application.getApplicationNote());
            vo.setReviewTime(application.getReviewTime());
            vo.setReviewNote(application.getReviewNote());
            vo.setCompleteTime(application.getCompleteTime());
            vo.setCompleteNote(application.getCompleteNote());

            // 获取申请者信息
            Student applicant = studentMapper.selectById(application.getApplicantId());
            if (applicant != null) {
                vo.setApplicantNickname(applicant.getNickname());
                vo.setApplicantAvatar(applicant.getAvatarUrl());
                vo.setApplicantPhone(applicant.getPhone());
                vo.setApplicantQq(applicant.getQq());
                vo.setApplicantWechat(applicant.getWechat());
            }

            return vo;
        }).collect(java.util.stream.Collectors.toList());
    }

    @Override
    public Page<LaborApplicationVO> getLaborApplicationsPage(Long laborId, Long publisherId, int page, int size) {
        // 验证发布者权限
        Labor labor = laborMapper.selectById(laborId);
        if (labor == null || !labor.getPublisherId().equals(publisherId)) {
            throw new RuntimeException("无权限查看此劳务的申请");
        }

        // 创建分页对象
        Page<LaborApplication> pageParam = new Page<>(page, size);

        QueryWrapper<LaborApplication> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("labor_id", laborId);
        queryWrapper.eq("deleted", 0);
        queryWrapper.orderByDesc("application_time");

        Page<LaborApplication> applicationPage = laborApplicationMapper.selectPage(pageParam, queryWrapper);

        // 转换为VO对象，包含申请者联系方式
        Page<LaborApplicationVO> voPage = new Page<>();
        voPage.setCurrent(applicationPage.getCurrent());
        voPage.setSize(applicationPage.getSize());
        voPage.setTotal(applicationPage.getTotal());
        voPage.setPages(applicationPage.getPages());

        List<LaborApplicationVO> voList = applicationPage.getRecords().stream().map(application -> {
            LaborApplicationVO vo = new LaborApplicationVO();
            vo.setId(application.getId());
            vo.setLaborId(application.getLaborId());
            vo.setJobTitle(labor.getJobTitle());
            vo.setLaborStatus(labor.getStatus());
            vo.setApplicantId(application.getApplicantId());
            vo.setApplicationTime(application.getApplicationTime());
            vo.setStatus(application.getStatus());
            vo.setStatusDescription(LaborApplicationStatus.fromCode(application.getStatus()).getDescription());
            vo.setApplicationNote(application.getApplicationNote());
            vo.setReviewTime(application.getReviewTime());
            vo.setReviewNote(application.getReviewNote());
            vo.setCompleteTime(application.getCompleteTime());
            vo.setCompleteNote(application.getCompleteNote());

            // 获取申请者信息
            Student applicant = studentMapper.selectById(application.getApplicantId());
            if (applicant != null) {
                vo.setApplicantNickname(applicant.getNickname());
                vo.setApplicantAvatar(applicant.getAvatarUrl());
                vo.setApplicantPhone(applicant.getPhone());
                vo.setApplicantQq(applicant.getQq());
                vo.setApplicantWechat(applicant.getWechat());
            }

            return vo;
        }).collect(java.util.stream.Collectors.toList());

        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean reviewApplication(Long applicationId, String status, String reviewNote, Long publisherId) {
        LaborApplication application = laborApplicationMapper.selectById(applicationId);
        if (application == null || application.getDeleted() == 1) {
            throw new RuntimeException("申请记录不存在");
        }

        // 验证发布者权限
        Labor labor = laborMapper.selectById(application.getLaborId());
        if (labor == null || !labor.getPublisherId().equals(publisherId)) {
            throw new RuntimeException("无权限审核此申请");
        }

        // 更新申请状态
        application.setStatus(status);
        application.setReviewTime(LocalDateTime.now());
        application.setReviewNote(reviewNote);

        laborApplicationMapper.updateById(application);

        // 如果接受申请，更新劳务的已接受申请数
        if ("accepted".equals(status)) {
            labor.setAcceptedCount(labor.getAcceptedCount() + 1);
            laborMapper.updateById(labor);
        }

        // 发送审核结果通知消息给申请者
        try {
            Student publisher = studentMapper.selectById(publisherId);
            String reviewerName = publisher != null ? publisher.getNickname() : "发布者";

            String reviewResult = "accepted".equals(status) ? "approved" : "rejected";

            messageService.sendLaborReviewMessage(
                    application.getApplicantId(),
                    labor.getId(),
                    labor.getJobTitle(),
                    reviewResult,
                    reviewNote,
                    publisherId,
                    reviewerName
            );
        } catch (Exception e) {
            log.warn("发送审核通知消息失败: {}", e.getMessage());
        }

        log.info("审核申请成功: applicationId={}, status={}, publisherId={}",
                applicationId, status, publisherId);

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean completeLabor(Long applicationId, String completeNote, Long userId) {
        LaborApplication application = laborApplicationMapper.selectById(applicationId);
        if (application == null || application.getDeleted() == 1) {
            throw new RuntimeException("申请记录不存在");
        }

        // 验证用户权限（申请者或发布者）
        Labor labor = laborMapper.selectById(application.getLaborId());
        if (labor == null) {
            throw new RuntimeException("劳务不存在");
        }

        if (!application.getApplicantId().equals(userId) && !labor.getPublisherId().equals(userId)) {
            throw new RuntimeException("无权限完成此劳务");
        }

        // 更新申请状态
        application.setStatus("completed");
        application.setCompleteTime(LocalDateTime.now());
        application.setCompleteNote(completeNote);

        laborApplicationMapper.updateById(application);

        log.info("完成劳务成功: applicationId={}, userId={}", applicationId, userId);

        return true;
    }

    @Override
    public Page<Labor> getMyPublishedLabors(Long publisherId, int page, int size) {
        Page<Labor> pageParam = new Page<>(page, size);

        QueryWrapper<Labor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("publisher_id", publisherId);
        queryWrapper.eq("deleted", 0);
        queryWrapper.orderByDesc("create_time");

        return laborMapper.selectPage(pageParam, queryWrapper);
    }

    @Override
    public Page<Labor> getMyPublishedLaborsByStatus(Long publisherId, String status, int page, int size) {
        Page<Labor> pageParam = new Page<>(page, size);

        QueryWrapper<Labor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("publisher_id", publisherId);
        queryWrapper.eq("status", status);
        queryWrapper.eq("deleted", 0);
        queryWrapper.orderByDesc("create_time");

        return laborMapper.selectPage(pageParam, queryWrapper);
    }

    @Override
    public Page<LaborApplication> getMyLaborApplications(Long applicantId, int page, int size) {
        Page<LaborApplication> pageParam = new Page<>(page, size);

        QueryWrapper<LaborApplication> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("applicant_id", applicantId);
        queryWrapper.eq("deleted", 0);
        queryWrapper.orderByDesc("application_time");

        return laborApplicationMapper.selectPage(pageParam, queryWrapper);
    }

    @Override
    public void incrementViewCount(Long id) {
        Labor labor = laborMapper.selectById(id);
        if (labor != null && labor.getDeleted() == 0) {
            labor.setViewCount(labor.getViewCount() + 1);
            laborMapper.updateById(labor);
        }
    }

    @Override
    public List<Labor> getHotLabors(int limit, Long schoolId) {
        QueryWrapper<Labor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        queryWrapper.eq("status", "recruiting"); // 只获取未完成的任务（招聘中）

        // 学校ID过滤（数据隔离）
        if (schoolId != null) {
            queryWrapper.eq("school_id", schoolId);
            log.info("获取热门劳务，添加学校ID过滤: schoolId={}", schoolId);
        } else {
            log.info("获取热门劳务时未提供学校ID，返回所有学校的热门劳务（支持未登录用户浏览）");
        }

        queryWrapper.orderByDesc("view_count"); // 按浏览次数降序排列
        queryWrapper.orderByDesc("create_time"); // 其次按创建时间降序排列
        queryWrapper.last("LIMIT " + limit);

        List<Labor> hotLabors = laborMapper.selectList(queryWrapper);

        // 为每个劳务设置发布者信息和申请人数
        for (Labor labor : hotLabors) {
            if (labor.getPublisherId() != null) {
                Student publisher = studentMapper.selectById(labor.getPublisherId());
                if (publisher != null) {
                    labor.setPublisher(publisher.getNickname());
                }
            }

            // 设置当前申请人数
            Long applicationCount = laborApplicationMapper.selectCount(
                    new LambdaQueryWrapper<LaborApplication>()
                            .eq(LaborApplication::getLaborId, labor.getId())
                            .eq(LaborApplication::getDeleted, 0)
            );
            labor.setApplicationCount(applicationCount);

            // 确保viewCount不为null
            if (labor.getViewCount() == null) {
                labor.setViewCount(0);
            }

            // 确保applyCount不为null
            if (labor.getApplyCount() == null) {
                labor.setApplyCount(0);
            }

            // 确保publisherType不为null
            // 如果publisherType为空，根据merchantId是否存在来判断
            if (labor.getPublisherType() == null || labor.getPublisherType().isEmpty()) {
                if (labor.getMerchantId() != null && labor.getMerchantId() > 0) {
                    labor.setPublisherType("merchant");
                } else {
                    labor.setPublisherType("student");
                }
            }

            LaborType laborType = laborTypeMapper.selectById(labor.getTypeId());
            if (laborType != null) {
                labor.setTypeName(laborType.getTypeName());
            }
        }

        return hotLabors;
    }

    @Override
    public com.campus.help.dto.LaborStats getLaborStats() {
        try {
            // 获取总发布数
            Long totalCount = laborMapper.selectCount(
                    new LambdaQueryWrapper<Labor>()
                            .eq(Labor::getDeleted, 0)
            );

            // 获取今日发布数
            java.time.LocalDate today = java.time.LocalDate.now();
            java.time.LocalDateTime startTime = today.atStartOfDay();
            java.time.LocalDateTime endTime = today.atTime(23, 59, 59);

            Long todayCount = laborMapper.selectCount(
                    new LambdaQueryWrapper<Labor>()
                            .eq(Labor::getDeleted, 0)
                            .between(Labor::getCreateTime, startTime, endTime)
            );

            log.info("劳务统计 - 总发布数: {}, 今日发布数: {}", totalCount, todayCount);

            return new com.campus.help.dto.LaborStats(totalCount, todayCount);
        } catch (Exception e) {
            log.error("获取劳务统计失败", e);
            throw new RuntimeException("获取劳务统计失败: " + e.getMessage(), e);
        }
    }
}
